/*
 * @ProjectName: 编程学习
 * @Copyright:   2019 HangZhou Yi Dev, Ltd. All Right Reserved.
 * @address:     http://Yi.tech
 * @date:        2019/4/29 23:28
 * @email:       xiazhaoyang@live.com
 * @description: 本内容仅限于编程技术学习使用，转发请注明出处.
 */
package com.example.auth.config.component;


import com.example.auth.common.constant.SecurityConstant;
import com.example.auth.dao.common.mapper.RoleRepository;
import com.example.auth.dao.common.model.Role;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *
 * </p>
 *
 * @author Yi
 * @version v1.0.0
 * @date 2019/4/29 23:28
 * @modificationHistory=========================逻辑或功能性重大变更记录
 * @modify By: {修改人} 2019/4/29
 * @modify reason: {方法名}:{原因}
 * ...
 */
@Component
public class AppListener implements ApplicationListener<ContextRefreshedEvent> {

    @Resource
    private RoleRepository roleRepository;

    /**
     * Handle an application event.
     *
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (Objects.isNull(event.getApplicationContext().getParent())) {
            initRoleConfig();
        }

    }

    /**
     * 初始化角色配置
     */
    private void initRoleConfig() {
        List<Role> roleList = roleRepository.findAll();
        if (CollectionUtils.isEmpty(roleList)) {
            roleRepository.saveAll(Arrays.asList(
                    Role.builder().roleDesc("系统管理员").roleName(SecurityConstant.ROLE_ADMIN).build(),
                    Role.builder().roleDesc("普通用户").roleName(SecurityConstant.ROLE_USER).build(),
                    Role.builder().roleDesc("黑名单用户").roleName(SecurityConstant.ROLE_FORBIDDEN).build(),
                    Role.builder().roleDesc("客户端").roleName(SecurityConstant.ROLE_ClIENT).build(),
                    Role.builder().roleDesc("授信客户端").roleName(SecurityConstant.ROLE_TRUST_ClIENT).build()
            ));
        }
    }
}